#ifndef GANTTCHARTVIEW_HPP
#define GANTTCHARTVIEW_HPP

#include <QWidget>
#include <QVBoxLayout>
#include <QDebug>
#include <limits>
#include <cmath> // 为了使用 std::ceil
#include "tool/TimeHelper.hpp"
#include "assembly/viewmodel/GanttChartViewModel.hpp"
#include "assembly/widget/PartsStackedBarWidget.hpp"
#include "store/struct/DurationCarrier.hpp"

QT_CHARTS_USE_NAMESPACE

class GanttChartView : public QWidget {
    Q_OBJECT

public:
    explicit GanttChartView(QWidget *parent = nullptr)
        : QWidget(parent),
          viewModel(new GanttChartViewModel(this)) { // 初始化 fixedOffset

        oViewUI();
        oConnections();
    }

    ~GanttChartView() override = default;

protected:
    void paintEvent(QPaintEvent *event) override {
        QWidget::paintEvent(event);
    }

    void resizeEvent(QResizeEvent *event) override {
        QWidget::resizeEvent(event);
        updateChart();
    }

private:
    void oViewUI() {
        layout = new QVBoxLayout(this);
    }

    void oConnections() {
        connect(viewModel, &GanttChartViewModel::startTimeChanged, this, &GanttChartView::updateChart);
        connect(viewModel, &GanttChartViewModel::endTimeChanged,   this, &GanttChartView::updateChart);
        connect(viewModel, &GanttChartViewModel::durationsChanged, this, &GanttChartView::updateChart);
    }

public slots:
    void updateChart() {
        QList<DurationCarrier> currentDurations = viewModel->getDurations();

        // 先清空布局内旧的 widget
        QLayoutItem* item;
        while ((item = layout->takeAt(0)) != nullptr) {
            if (item->widget()) {
                item->widget()->deleteLater();
            }
            delete item;
        }

        stackedBarWidget = new PartsStackedBarWidget(-1, -1, this);
        stackedBarWidget->setPartsStackedData(currentDurations);
        layout->addWidget(stackedBarWidget);

    }

private:
    GanttChartViewModel *viewModel;
    PartsStackedBarWidget *stackedBarWidget;
    QVBoxLayout *layout = nullptr;

};

#endif // GANTTCHARTVIEW_HPP
